#include "receipt.h"
#include "ui_receipt.h"

Receipt::Receipt(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Receipt)
{
    ui->setupUi(this);

    table=TD_RECEIPT;

    listModel=new QStringListModel(this);
    ui->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    ui->tableView->setModel(model);

    updateMonth();
    createMenu();
    updateView();
}

Receipt::~Receipt()
{
    delete ui;
}

void Receipt::updateMonth()
{
    auto monthList=sp_getCategory("month_",table);
    listModel->setStringList(monthList);
}

void Receipt::generateMenu()
{
    menu->addAction(QStringLiteral("新增... (F1)"),this,&Receipt::newItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新月份 (F4)"),this,&Receipt::updateMonth);
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&Receipt::updateView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("撤销 (Ctrl+Z)"),this,&Receipt::revert);
    menu->addAction(QStringLiteral("保存 (Ctrl+S)"),this,&Receipt::save);
}

void Receipt::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key()==Qt::Key_S)
        save();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
        revert();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F4:
            updateMonth();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        }
    }
}

void Receipt::newItem()
{
    Receipt_AddItem item(this);
    if(item.exec() == QDialog::Accepted)
        updateView();
}

void Receipt::updateView()
{
    if(selectMonth.isEmpty())
        selectMonth=CurrentMonth;

    model->setTable(table);
    model->setFilter(QString("month_ ='%1'").arg(selectMonth));
    model->select();
    setHeaderData();
}

void Receipt::setHeaderData()
{
    ui->tableView->hideColumn(0);
    ui->tableView->hideColumn(1);   //month_
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("发票号"));
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("开票日期"));
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("开票金额"));
    model->setHeaderData(6,Qt::Horizontal,QStringLiteral("发票来源"));
    ui->tableView->hideColumn(7);   //status
}

void Receipt::on_vouchNo_returnPressed()
{
    QString vouchNo=ui->vouchNo->text().trimmed();
    model->setTable(table);
    model->setFilter(QString("vouch_no like '%%1%'").arg(vouchNo));
    model->select();
    setHeaderData();
}

void Receipt::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        selectMonth=index.data().toString();
        updateView();
    }
}
